package com.feihe.service;

import com.feihe.dto.AdminQueryRequest;
import com.feihe.entity.Admin;
import com.feihe.entity.Calendar;
import com.feihe.entity.Reservation;
import com.feihe.repository.AdminRepository;
import com.feihe.repository.CalendarRepository;
import com.feihe.repository.ReservationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AdminService {
    
    @Autowired
    private AdminRepository adminRepository;
    
    @Autowired
    private CalendarRepository calendarRepository;
    
    @Autowired
    private ReservationRepository reservationRepository;
    
    /**
     * 管理员登录验证
     */
    public boolean login(String username, String password) {
        if (username == null || username.trim().isEmpty()) {
            throw new RuntimeException("请输入账号");
        }
        
        if (password == null || password.trim().isEmpty()) {
            throw new RuntimeException("请输入密码");
        }
        
        // 查找管理员
        Admin admin = adminRepository.findByAdminUsername(username.trim());
        if (admin == null) {
            throw new RuntimeException("账号或密码错误");
        }
        
        // 验证密码（MD5加密）
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!encryptedPassword.equals(admin.getAdminPassword())) {
            throw new RuntimeException("账号或密码错误");
        }
        
        return true;
    }
    
    /**
     * 添加日历状态
     */
    public void addCalendarStatus(Integer status, String startTime, String endTime) {
        LocalDateTime start = LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime end = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        
        Calendar calendar = new Calendar();
        calendar.setStartTime(start);
        calendar.setEndTime(end);
        calendar.setStatus(status);
        
        calendarRepository.save(calendar);
    }
    
    /**
     * 删除预约
     */
    public void deleteReservation(Long id) {
        reservationRepository.deleteById(id);
    }
    
    /**
     * 查询预约和日历数据
     */
    public List<Map<String, Object>> queryReservationsAndCalendars(AdminQueryRequest request) {
        List<Map<String, Object>> data = new ArrayList<>();
        
        LocalDateTime startTime = LocalDateTime.parse(request.getStartTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime endTime = LocalDateTime.parse(request.getEndTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        
        // 查询预约数据（如果is_open = 1）
        if (request.getIsOpen() != null && request.getIsOpen() == 1) {
            List<Reservation> reservations = reservationRepository.findByReservationStartTimeBetween(startTime, endTime);
            
            for (Reservation reservation : reservations) {
                Map<String, Object> item = new HashMap<>();
                item.put("reservation", 1);
                item.put("realname", reservation.getRealname());
                item.put("telephone", reservation.getTelephone());
                item.put("visitor_number", reservation.getVisitorNumber());
                item.put("start_time", reservation.getReservationStartTime().toString().replace(" ", "T"));
                item.put("end_time", reservation.getReservationEndTime().toString().replace(" ", "T"));
                item.put("type", reservation.getType());
                data.add(item);
            }
        }
        
        // 查询日历状态数据
        List<Calendar> calendars = calendarRepository.findByStartTimeBetween(startTime, endTime);
        
        for (Calendar calendar : calendars) {
            Map<String, Object> item = new HashMap<>();
            item.put("reservation", 0);
            item.put("start_time", calendar.getStartTime().toString().replace(" ", "T"));
            item.put("end_time", calendar.getEndTime().toString().replace(" ", "T"));
            item.put("status", getStatusText(calendar.getStatus()));
            data.add(item);
        }
        
        return data;
    }
    
    /**
     * 获取状态文本
     */
    private String getStatusText(Integer status) {
        switch (status) {
            case 1: return "维护";
            case 2: return "系统升级";
            case 3: return "维修";
            case 4: return "闭馆";
            case 5: return "内部活动";
            default: return "未知状态";
        }
    }
    
    /**
     * 获取所有预约列表
     */
    public List<Map<String, Object>> getAllReservations() {
        List<Reservation> reservations = reservationRepository.findAll();
        List<Map<String, Object>> result = new ArrayList<>();
        
        for (Reservation reservation : reservations) {
            Map<String, Object> item = new HashMap<>();
            item.put("id", reservation.getId());
            item.put("realname", reservation.getRealname());
            item.put("telephone", reservation.getTelephone());
            item.put("visitor_number", reservation.getVisitorNumber());
            item.put("ground", reservation.getGround());
            item.put("type", reservation.getType());
            item.put("reservation_start_time", reservation.getReservationStartTime());
            item.put("reservation_end_time", reservation.getReservationEndTime());
            item.put("is_check", reservation.getIsCheck());
            item.put("create_time", reservation.getCreateTime());
            result.add(item);
        }
        
        return result;
    }
    
    public List<Map<String, Object>> getFilteredReservations(String date, String search, Integer type) {
        List<Reservation> reservations = reservationRepository.findAll();
        
        // 过滤结果
        List<Reservation> filteredReservations = reservations.stream()
                .filter(reservation -> {
                    // 日期过滤
                    if (date != null && !date.trim().isEmpty()) {
                        try {
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                            LocalDate filterDate = LocalDate.parse(date, formatter);
                            LocalDateTime startOfDay = filterDate.atStartOfDay();
                            LocalDateTime endOfDay = filterDate.atTime(23, 59, 59);
                            
                            if (reservation.getReservationStartTime().isBefore(startOfDay) || 
                                reservation.getReservationStartTime().isAfter(endOfDay)) {
                                return false;
                            }
                        } catch (Exception e) {
                            // 日期格式错误，跳过此过滤条件
                        }
                    }
                    
                    // 搜索过滤（姓名或电话）
                    if (search != null && !search.trim().isEmpty()) {
                        String searchLower = search.toLowerCase();
                        boolean nameMatch = reservation.getRealname() != null && 
                                reservation.getRealname().toLowerCase().contains(searchLower);
                        boolean phoneMatch = reservation.getTelephone() != null && 
                                reservation.getTelephone().contains(search);
                        if (!nameMatch && !phoneMatch) {
                            return false;
                        }
                    }
                    
                    // 类型过滤
                    if (type != null && !type.equals(reservation.getType())) {
                        return false;
                    }
                    
                    return true;
                })
                .collect(Collectors.toList());
        
        // 转换为Map格式
        List<Map<String, Object>> result = new ArrayList<>();
        for (Reservation reservation : filteredReservations) {
            Map<String, Object> item = new HashMap<>();
            item.put("id", reservation.getId());
            item.put("realname", reservation.getRealname());
            item.put("telephone", reservation.getTelephone());
            item.put("visitor_number", reservation.getVisitorNumber());
            item.put("ground", reservation.getGround());
            item.put("type", reservation.getType());
            item.put("reservation_start_time", reservation.getReservationStartTime());
            item.put("reservation_end_time", reservation.getReservationEndTime());
            item.put("is_check", reservation.getIsCheck());
            item.put("create_time", reservation.getCreateTime());
            result.add(item);
        }
        
        return result;
    }
} 